<?php
use think\Config;
use Think\Db;
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 * @author jry <416148489@qq.com>
 */
function user_md5($str, $auth_key=null)
{
    if (!$auth_key) {
        $auth_key = Config::get('AUTH_KEY') ?: '0755web';
    }
    return '' === $str ? '' : md5(sha1($str) . $auth_key);
}

/**
 * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @param mixed $default 默认值
 * @return mixed
 */
function C($name=null, $value=null,$default=null) {

    static $_config = array();
    // 无参数时获取所有
    if (empty($name)) {
        return $_config;
    }
    // 优先执行设置获取或赋值
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtoupper($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : $default;
            $_config[$name] = $value;
            return null;
        }
        // 二维数组设置和获取支持
        $name = explode('.', $name);
        $name[0]   =  strtoupper($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
        $_config[$name[0]][$name[1]] = $value;
        return null;
    }
    // 批量设置
    if (is_array($name)){
        $_config = array_merge($_config, array_change_key_case($name,CASE_UPPER));
        return null;
    }
    return null; // 避免非法参数
}

/** 12:34 字符串转数组
 * @param $options
 * @return array
 */
 function string_change_arr($options){

    $data = explode('-',$options);
    if(empty($data[0])){ $data[0]="00:00"; }
    if(empty($data[1])){ $data[1]="23:50"; }

    return $data;
}


/**
 * 会员积分、余额变化记录
 * @param $masterId 主变化用户ID
 * @param $deputyId 被变化用户ID
 * @param $accountNum 变化量
 * @param $getType 变化详细类型
 * @param $nowAllNum 变化后总量
 * @param $type 变化类型，默认余额
 */
function addAccountRecords($masterId,$deputyId,$accountNum,$getType,$nowAllNum,$type = 'money',$oldNum){
    $moneyData = [
        'master_id' => $masterId,
        'deputy_id' => $deputyId,
        'get_nums' => $accountNum,
        'get_type' => $getType,
        'now_nums' => $nowAllNum,
        'old_nums'=>$oldNum,
    ];

    $tableName = 'user'.$type.'_record';

    $status = Db::name($tableName)->insert($moneyData);

    return $status;

}

//等级做成可配置
/**
 * @param $uid
 * @param $useGrade
 * @param $isDegraded
 * @return int
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function formatLevel($uid, $useGrade, $isDegraded,$scores=null,$moneys=null)
{
    $user = Db::name('User');
    $store = Db::name('store');
    if(!$scores || !$moneys) {
        $where['uid'] = array('EQ', $uid);
        $info = $store->where($where)->Field('fengmi_num,cangku_num')->find();
        $scores = $info['fengmi_num'];//积分
        $moneys = $info['cangku_num'];//零钱
    }
    //获取配置等级数据
    $configValue = Db::name('levelconfig')->field('level,money,score,user_lev,user_num')->select();
    $configData = [];
    foreach ($configValue as $key => $val) {
        $configData[$val['level']]['user_num'] = $val['user_num'];
        $configData[$val['level']]['score'] = $val['score'];
        $configData[$val['level']]['money'] = $val['money'];
        $configData[$val['level']]['user_lev'] = $val['user_lev'];
    }

    //积分条件
    $jiLevel = 1;
    switch ($scores) {//用户积分 判断级别的积分对比 (用户积分<500) 返回 -1
        case bccomp($scores, $configData[2]['score'], 5) < 0:
            $jiLevel = 1;
            break;
        case bccomp($scores, $configData[2]['score'], 5) >= 0 && bccomp($scores, $configData[3]['score'], 5) < 0:
            $jiLevel = 2;
            break;
        case bccomp($scores, $configData[3]['score'], 5) >= 0 && bccomp($scores, $configData[4]['score'], 5) < 0:
            $jiLevel = 3;
            break;
        case bccomp($scores, $configData[4]['score'], 5) >= 0 && bccomp($scores, $configData[5]['score'], 5) < 0:
            $jiLevel = 4;
            break;
        case bccomp($scores, $configData[5]['score'], 5) >= 0 && bccomp($scores, $configData[6]['score'], 5) < 0:
            $jiLevel = 5;
            break;
        case bccomp($scores, $configData[6]['score'], 5) >= 0:
            $jiLevel = 6;
            break;
    }
    //余额条件
    $yuLevel = 1;
    switch ($moneys) {
        case bccomp($moneys, $configData[2]['money'], 5) < 0:
            $yuLevel = 1;
            break;
        case bccomp($moneys, $configData[2]['money'], 5) >= 0 && bccomp($moneys, $configData[3]['money'], 5) < 0:
            $yuLevel = 2;
            break;
        case bccomp($moneys, $configData[3]['money'], 5) >= 0 && bccomp($moneys, $configData[4]['money'], 5) < 0:
            $yuLevel = 3;
            break;
        case bccomp($moneys, $configData[4]['money'], 5) >= 0 && bccomp($moneys, $configData[5]['money'], 5) < 0:
            $yuLevel = 4;
            break;
        case bccomp($moneys, $configData[5]['money'], 5) >= 0 && bccomp($moneys, $configData[6]['money'], 5) < 0:
            $yuLevel = 5;
            break;
        case bccomp($moneys, $configData[6]['money'], 5) >= 0:
            $yuLevel = 6;
            break;
    }


    //取出推荐了多少人
    $userWhere = [
        'pid' => $uid,
    ];
    $userWhere['use_grade'] = [
        'egt', $configData[1]['user_lev']
    ];
    $tUserCountOne = $user->where($userWhere)->count();//推荐了多少人

    $userWhere['use_grade'] = [
        'egt', $configData[2]['user_lev']
    ];
    $tUserCountTwo = $user->where($userWhere)->count();

    $userWhere['use_grade'] = [
        'egt', $configData[3]['user_lev']
    ];
    $tUserCountThree= $user->where($userWhere)->count();

    $userWhere['use_grade'] = [
        'egt', $configData[4]['user_lev']
    ];
    $tUserCountFour = $user->where($userWhere)->count();

    $userWhere['use_grade'] = [
        'egt', $configData[5]['user_lev']
    ];
    $tUserCountFive = $user->where($userWhere)->count();

    $userWhere['use_grade'] = [
        'egt', $configData[6]['user_lev']
    ];
    $tUserCountSix = $user->where($userWhere)->count();

    //判断是属于哪个等级，默认为志愿者
    $userLevel =1;
    if($jiLevel>=1 && $yuLevel>=1  && $tUserCountOne >= $configData[1]['user_num']){
        $userLevel = 1;
    }
    if($jiLevel>=2 && $yuLevel>=2 && $tUserCountTwo >= $configData[2]['user_num'] ){
        $userLevel = 2;
    }
    if($jiLevel>=3 && $yuLevel>=3 && $tUserCountThree >= $configData[3]['user_num']){
        $userLevel = 3;
    }
    if($jiLevel>=4 && $yuLevel>=4 && $tUserCountFour >= $configData[4]['user_num']){
        $userLevel = 4;
    }
    if($jiLevel>=5 && $yuLevel>=5 && $tUserCountFive >= $configData[5]['user_num']){
        $userLevel = 5;
    }
    if($jiLevel>=6 && $yuLevel>=6 && $tUserCountSix >= $configData[6]['user_num']){
        $userLevel = 6;
    }



    if($isDegraded != 1){
        //不忽略降级操作
        $arr =  uUserLevel($uid,$userLevel);
    }else{
        //忽略降级操作
        if($userLevel > $useGrade){
            $arr =   uUserLevel($uid,$userLevel);
        }
    }

    if(!isset($arr)){
        return 1;
    }
    return $arr;

}


function uUserLevel($uid,$level){
    $userModel = Db::name('user');

    $where = 'userid = '.$uid;
    $userGrade = $userModel->where($where)->field('use_grade')->find()['use_grade'];
    if($userGrade!=$level){
        $name = $userModel->where($where)->update(['use_grade'=>$level]);
        if(!$name){
            return 0;
        }

    }
    return 1;

}
function AddUserLevel($uid){
    $where['uid']=$uid;
    //直推人数
    $table = Db::name('user_level');
    $info=$table->where($where)->field('children_num,land_num,user_level')->find();
    $children_count=$info['children_num'];
    $land_count=$info['land_num'];
    if($land_count>=1){
        $level=1;
    }
    if($land_count>=10 && $children_count>=10){
        $level=2;
    }
    if($land_count>=15 && $children_count>=20){
        $level=3;
    }
    if($land_count>=15 && $children_count>=30){
        $level=4;
    }
    if($land_count>=15 && $children_count>=40){
        $level=5;
    }
    if($land_count>=15 && $children_count>=60){
        $level=5;
    }
    //低等级才修改
    if($level && $info['user_level']<$level){
        $table->where($where)->setField('user_level',$level);
    }

}

/**
 * [user_salt 用户密码加密链接串]
 * @return [type] [description]
 */
function user_salt($time=null){
    if(isset($time) || empty($time)){
        $time=time();
    }
    return substr(md5($time),0,3);
}
//获取用户ip
function get_cip(){
    $cip = '';
    if(!empty($_SERVER["HTTP_CLIENT_IP"]))
    {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    }
    else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
    {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    else if(!empty($_SERVER["REMOTE_ADDR"]))
    {
        $cip = $_SERVER["REMOTE_ADDR"];
    }
    return $cip;
}

/**
 * [pwdMd5 用户密码加密]
 *
 */
function pwdMd5($value, $salt)
{
    $user_pwd = md5(md5($value) . $salt);
    return $user_pwd;
}
// @return integer 0-未登录，大于0-当前登录用户ID
 function user_login()
{
    $user = session('user_login');
    if (empty($user)) {
        return 0;
    } else {
        if (session('user_login_sign') == data_auth_sign($user)) {
            return $user['userid'];
        } else {
            return 0;
        }
    }
}


/**
 * 数据签名认证
 * @param  array $data 被认证的数据
 * @return string       签名
 *
 */
function data_auth_sign($data)
{
    // 数据类型检测
    if (!is_array($data)) {
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); // url编码并生成query字符串
    $sign = sha1($code); // 生成签名
    return $sign;
}

/**
 * 获取和设置语言定义(不区分大小写)
 * @param string|array $name 语言变量
 * @return mixed
 */
function L($name=null)
{
  /*  if (empty($name))  return $name;
    $name = strtolower($name);
    $lang_type = cookie('think_language');
    $lang = ['1'=>'en-us','2'=> 'zxcghy84-corean', '3'=>'zxcghy84-jp','4'=>'zh-cn'];
    if (!in_array($lang_type,$lang)){
        $lang_type = $lang[4];
    }*/

    $lang_arr = lnag_ty();

    return isset($lang_arr[$name]) ? $lang_arr[$name] : strtoupper($name);

}
//获取语言
//
//  $data['type'] 当前的语言
//  $data['lang']所有语言
 function get_lang($param_name,$type=null)
 {
     if(empty($param_name)){  return ''; }
     $lang_type = ['1' => 'en-us', '2' => 'zxcghy84-corean', '3' => 'zxcghy84-jp', '4' => 'zh-cn'];

      $name = $param_name.'_name';
     $sendType = cookie('think_language');

     if (!in_array($sendType, $lang_type)) {  $sendType = 'zh-cn'; }

   //  require WEB_ROOT . '/system/data/lang/Lang/'. $sendType.'.php ';
     $lang_arr = lnag_ty();

     /*if(in_array($param_name,['turnout','change_out','exehange','share'])){
         $data['user_info'] = $lang_arr['user_info'];
     }*/

     $data[$name] = $lang_arr["$name"];
     if(!empty($type)) {
         $data['lang_all'] = ['en-us' => 'English', 'zxcghy84-corean' => '한국어', 'zxcghy84-jp' => 'わぶん', 'zh-cn' => '中文'];
         $data['lang_type'] = $sendType;//当前选中的语言
         $data['vesion'] = DREAM_VERSION;//版本号
     }
     return $data;
}
//判断TOKEN
function checkToken($token) {

    if ($token == session('TOKEN')) {
        session('TOKEN', NULL);
        return 1;
    } else {
        return 0;
    }
}

//创建TOKEN
function creatToken() {
    $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
    session('TOKEN', authcode($code));
    return authcode($code);
}
/* 加密TOKEN */
function authcode($str) {
    $key = "ANDIAMON";
    $str = substr(md5($str), 8, 10);
    return md5($key . $str);
}


function success_alert($mes,$url=''){
    if($url!=''){
        echo "<meta charset=\"utf-8\"/><script>alert('".$mes."');location.href='" .$url. "';</script>";
    }else{
        echo "<meta charset=\"utf-8\"/><script>alert('".$mes."');location.href='" .$jumpUrl. "';</script>";
    }
    exit;
}

//生成唯一订单
function build_order_no()
{
    $no = 'PAY' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    //检测是否存在
    $db = Db::name('trans');
    $count = $db->where(array('pay_no' => $no))->count(1);
    ($count > 0) && $no = build_order_no();
    return $no;
}


// 发送短信验证
function sendMsg($mobile,$sendType)
{
    if (time() > session('set_time') + 300 || session('set_time') == '') {
        session('set_time', time());
        $user_mobile = $mobile;
        $code =  rand(111111, 99999);//获取随机验证码
        $sms_code = sha1(md5(trim($code) . trim($mobile)));
        session('sms_code', $sms_code);//将验证码和手机号存入

        //发送短信
//        $content="您本次的验证码为".$code."，请在5分钟内完成验证，验证码打死也不要告诉别人哦！";//要发送的短信内容
      /*  if($sendType == 'zxcghy84-corean'){
            $user_mobile = '0082'.$user_mobile;
            $res = sendSms($user_mobile,$code);
            if($res->Code=='OK'){
                $res = 0;
            }else{
                $res = 1;
            }
        }*/
        $res = newMsg($user_mobile,$code);//发送短信

        if ($res == 0) {
            $sms = ['sms_type'=>1,'sms_code'=>$code,'mobile'=>$mobile,'sms_time'=>time()];
            Db::name('sms_code')->insert($sms);

            return  L('dxfscg');
        } else {

            return  L( 'dxfssb');
        }
    } else {
        $msgtime = session('set_time') + 300 - time();
        $data = $msgtime . L('mzhzs');
        return $data;
    }
}


/* 短信发送接口
 * 聚合数据（JUHE.CN）短信API服务接口PHP请求示例源码
***DATE:2015-05-25
 * */
function newMsg($mobile,$code) {

    header('content-type:text/html;charset=utf-8');

    $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
    // $content=M('config','nc')->where(array('name'=>'MSG'))->getField('value');
    $key = Db::table('ncconfig')->where(array('name'=>'MSG_account'))->field('value')->find()['value'];
    $tpl_id = Db::table('ncconfig')->where(array('name'=>'MSG_password'))->field('value')->find()['value'];
    $contents='#code#='.$code;//要发送的短信内容
    $smsConf = array(
        'key'   => $key, //您申请的APPKEY
        'mobile'    => $mobile, //接受短信的用户手机号码
        'tpl_id'    => $tpl_id, //您申请的短信模板ID，根据实际情况修改
        'tpl_value' =>urldecode($contents), //您设置的模板变量，根据实际情况修改
    );

    $content = juhecurl($sendUrl,$smsConf,1); //请求发送短信

    if($content){
        $result = json_decode($content,true);
        $error_code = $result['error_code'];
        if($error_code == 0){
            //状态为0，说明短信发送成功
            // echo "短信发送成功,短信ID：".$result['result']['sid'];
            $mes=0 ;
        }else{
            //状态非0，说明失败
            $mes=1 ;
            // $msg = $result['reason'];
            // echo "短信发送失败(".$error_code.")：".$msg;
        }
    }else{
        //返回内容异常，以下可根据业务逻辑自行修改
        // echo "请求发送短信失败";
        $mes=1;
    }
    return $mes;

}

/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url,$params=false,$ispost=0){
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}
function setmyCode($mobile, $msg)
{
    $url = "http://service.winic.org:8009/sys_port/gateway/index.asp?";
    $data = "id=%s&pwd=%s&to=%s&content=%s&time=";
    $id = 'yxnongchang';
    $pwd = '123456web';
    $to = $mobile;
    $content = iconv("UTF-8", "GB2312", $msg);
    $rdata = sprintf($data, $id, $pwd, $to, $content);


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $rdata);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = substr($result, 0, 3);
    if ($result == '000') {
        return true;
    } else {
        return false;
    }
}


/*******=邮箱验证=**********/

/*
 * 发送邮箱并检验
 * @$sentTo发送人
 */
function sendPost($sentTo){
    //1成功其他有问题
    $set_time = session('set_time');

    //获取时间
    if(time()>$set_time+300 || $set_time == ''){//若 时间大于一分钟 或者时间为空的话
          return $result = sendEmail($sentTo); //返回1正确和2错误 那么调用发送邮件方法

    }else{

        $msgtime = session('set_time') + 300 - time();
        $data = $msgtime . L('mzhzs');
        return $data;
    }
}



function adminLog($sql,$content){
    $config = Config::get('database');//判断日志记录表是否安装
    $prefix = $config['prefix'];
    $exist = Db::query('show tables like "'.$prefix.'admin_log"');

    if (empty($exist)){ return null; }
    $request =  $_SERVER['HTTP_HOST'].'/'.$_SERVER['PATH_INFO'];
    $admin_id =  cmf_get_current_admin_id();
    $user = Db::name('user')->where('id',$admin_id)->field('user_login')->find();

    $data = [
        'user_id'=>$admin_id,
        'user_name'=>$user['user_login'],//管理员名称
        'ip'=>get_cip(),//ip
        'request'=>$request,//'url地址',
        'param'=>$sql,//参数
        'content'=>$content,//描述
        'addtime'=>time()
        ];
    Db::name('admin_log')->insert($data);
}

